package cn.tedu.seckill.controller;

import cn.tedu.seckill.mapper.SecMapper;
import com.jt.common.pojo.Seckill;
import com.jt.common.pojo.Success;
import com.jt.common.vo.SysResult;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/seckill/manage")
public class SecController {
    @Autowired
    SecMapper secMapper;

    @Autowired
    RabbitTemplate template;

    @RequestMapping("/list")
    public List<Seckill> queryAll() {
        return secMapper.selectAll();
    }

    @RequestMapping("/detail")
    public Seckill queryOne(String seckillId) {
        return secMapper.selectOne(Long.parseLong(seckillId));
    }

    /**
     * 作为前端系统接收秒杀请求，第一时间封装好参数，作为发送给交换机
     */
    @RequestMapping("{seckillId}")
    public SysResult seckill(@PathVariable Long seckillId) {
        try {
            // 封装消息，表示谁秒杀了什么, 如果是从登录状态获取用户信息，cookie获取，连接redis，拿到userJson 解析数据userId等
            // 现在模拟一个电话号码
            String userPone = "1330011" + RandomUtils.nextInt(9999);
            // 将表示用户身份的电话拼接到seckillId之后
            String msg = userPone + "/" + seckillId;
            template.convertAndSend("seckillD01", "seckill", msg);
            return SysResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return SysResult.build(201, "seckill failed", null);
        }
    }

    @RequestMapping("{seckillId}/userPhone")
    public List<Success> querySuccess(@PathVariable Long seckillId) {
        return secMapper.selectSuccess(seckillId);
    }
}
